import { Object3D, Vector3 } from "three";
import * as THREE from 'three'
import { IEditorHistoryOptions } from "../EditorHistory";
import EditorCommand, { EnumEditorCommandName, EnumEditorCommandType, IEditorCommandOutput } from "./EditorCommands";
export interface IEditorSetRotateCommandsOptions extends IEditorHistoryOptions {
    object: Object3D,
    newRotation: THREE.Euler,
    oldRotation: THREE.Euler
}
export const EVENT_EDITOR_SET_ROTATE_COMMANDS = "EVENT_EDITOR_SET_ROTATE_COMMANDS"
export default class EditorSetRotateCommands extends EditorCommand {
    object: Object3D;
    newRotation: THREE.Euler = new THREE.Euler();
    oldRotation: THREE.Euler = new THREE.Euler();
    constructor(options: IEditorSetRotateCommandsOptions) {
        super(options);
        let { object, newRotation, oldRotation } = options;
        this.type = EnumEditorCommandType.SetRotateCommand;
        this.name = EnumEditorCommandName.SetRotate;
        this.object = options.object;
        if (object !== undefined && newRotation !== undefined) {
            this.oldRotation = object.rotation.clone();
            this.newRotation = newRotation.clone();
        }
        if (oldRotation !== undefined) {
            this.oldRotation = oldRotation.clone();
        }
    }
    execute() {
        this.object.rotation.copy(this.newRotation);
        this.object.updateMatrixWorld(true);
        this.editor.$emit(EVENT_EDITOR_SET_ROTATE_COMMANDS, this.newRotation)
    }
    undo() {
        this.object.rotation.copy(this.oldRotation);
        this.object.updateMatrixWorld(true);
        this.editor.$emit(EVENT_EDITOR_SET_ROTATE_COMMANDS, this.oldRotation)
    }
    update(command: EditorSetRotateCommands) {
        this.newRotation.copy(command.newRotation);
    }

    toJSON() {
        const output: IEditorCommandOutput = {
            ...super.toJSON(),
            uuid: this.object.uuid,
            oldRotation: this.oldRotation.toArray() as [number, number, number],
            newRotation: this.newRotation.toArray() as [number, number, number]
        };
        return output;
    }

    fromJSON(json: IEditorCommandOutput) {
        super.fromJSON(json);
        let object = this.editor.objectByUuid(json.uuid!);
        if (object) {
            this.object = object;
            this.oldRotation = new THREE.Euler().fromArray([...json.oldRotation!]);
            this.newRotation = new THREE.Euler().fromArray([...json.newRotation!]);
        } else {
            throw new Error('找不到uuid对应的对象')
        }
    }

}